<template>
  <div class="glass-system-page">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-icon">
            <svg-icon icon-class="build" />
          </div>
          <div class="title-content">
            <h1>区域管理</h1>
            <p>Region Management - 建筑区域信息管理</p>
          </div>
        </div>
        <div class="header-actions">
          <button class="glass-button glass-button--warning" @click="handleResetStatus" v-hasPermi="['region:region:edit']">
            <svg-icon icon-class="refresh" />
            <span>重置状态</span>
          </button>
          <button class="glass-button glass-button--primary" @click="handleAddTopLevel" v-hasPermi="['region:region:add']">
            <svg-icon icon-class="plus" />
            <span>新增区域</span>
          </button>
        </div>
      </div>
    </div>

    <!-- Search Form -->
    <div class="search-form" v-show="showSearch">
      <div class="glass-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="区域名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入区域名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="区域状态" prop="regionStatus">
            <el-select v-model="queryParams.regionStatus" placeholder="请选择区域状态" clearable style="width: 200px">
              <el-option
                v-for="dict in region_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <button type="button" class="glass-button glass-button--primary" @click="handleQuery">
              <svg-icon icon-class="search" />
              <span>搜索</span>
            </button>
            <button type="button" class="glass-button" @click="resetQuery" style="margin-left: 8px;">
              <svg-icon icon-class="refresh" />
              <span>重置</span>
            </button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- Action Bar -->
    <div class="action-bar">
      <div class="action-content">
        <div class="action-buttons">
          <button class="glass-button" @click="toggleExpandAll">
            <svg-icon icon-class="sort" />
            <span>{{ isExpandAll ? '折叠' : '展开' }}全部</span>
          </button>
        </div>
        <div class="action-tools">
          <div class="tool-item" @click="showSearch = !showSearch">
            <svg-icon icon-class="search" />
            <span>显示搜索</span>
          </div>
          <div class="tool-item" @click="getList">
            <svg-icon icon-class="refresh" />
            <span>刷新</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Data Table -->
    <div class="data-table">
      <div class="table-container">
        <el-table
          v-if="refreshTable"
          v-loading="loading"
          :data="regionList"
          row-key="id"
          :default-expand-all="isExpandAll"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column label="区域名称" prop="name" min-width="200">
            <template #default="scope">
              <div class="region-name">
                <svg-icon icon-class="location" class="region-icon" />
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="区域状态" align="center" prop="regionStatus" width="120">
            <template #default="scope">
              <span :class="['glass-status-tag', getStatusClass(scope.row.regionStatus)]">
                {{ getStatusText(scope.row.regionStatus) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template #default="scope">
              <div class="table-actions">
                <el-tooltip 
                  :content="isProtectedRegion(scope.row) ? '系统保护的区域不可修改' : '修改'" 
                  placement="top"
                  :disabled="isProtectedRegion(scope.row)"
                >
                  <button 
                    class="action-btn action-btn--primary" 
                    @click="handleUpdate(scope.row)" 
                    v-hasPermi="['region:region:edit']"
                    :disabled="isProtectedRegion(scope.row)"
                    :class="{ 'action-btn--disabled': isProtectedRegion(scope.row) }"
                  >
                    <svg-icon icon-class="edit" />
                  </button>
                </el-tooltip>
                <el-tooltip 
                  v-if="isProtectedRegion(scope.row)"
                  :content="canAddSubRegion(scope.row) ? '新增子区域' : '只有县级单位才能新增子区域'" 
                  placement="top"
                  :disabled="!canAddSubRegion(scope.row)"
                >
                  <button 
                    class="action-btn action-btn--region-glass" 
                    @click="handleAdd(scope.row)" 
                    v-hasPermi="['region:region:add']"
                    :disabled="!canAddSubRegion(scope.row)"
                    :class="{ 'action-btn--disabled': !canAddSubRegion(scope.row) }"
                  >
                    <svg-icon icon-class="add" />
                  </button>
                </el-tooltip>
                <el-tooltip 
                  :content="isProtectedRegion(scope.row) ? '系统保护的区域不可删除' : '删除'" 
                  placement="top"
                  :disabled="isProtectedRegion(scope.row)"
                >
                  <button 
                    class="action-btn action-btn--danger" 
                    @click="handleDelete(scope.row)" 
                    v-hasPermi="['region:region:remove']"
                    :disabled="isProtectedRegion(scope.row)"
                    :class="{ 'action-btn--disabled': isProtectedRegion(scope.row) }"
                  >
                    <svg-icon icon-class="delete" />
                  </button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加或修改区域信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="regionRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="归属区域" prop="parentId">
          <div class="region-selector">
            <el-cascader
              v-model="form.regionPath"
              :options="chinaRegionOptions"
              :props="cascaderProps"
              placeholder="请选择省份-城市-县区"
              clearable
              filterable
              style="width: 100%"
              @change="handleRegionChange"
            />
            <div v-if="form.regionPath && form.regionPath.length > 0" class="region-info">
              <span class="region-path">{{ getRegionPathText() }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域状态" prop="regionStatus">
          <el-radio-group v-model="form.regionStatus" :disabled="form.isParentNode">
            <el-radio
              v-for="dict in region_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Region">
import { listRegion, getRegion, delRegion, addRegion, updateRegion } from "@/api/region/region"
import { runJob } from "@/api/monitor/job"
import { chinaRegionData } from "@/utils/chinaRegionData"

const { proxy } = getCurrentInstance()
const { region_status } = proxy.useDict('region_status')

const regionList = ref([])
const regionOptions = ref([])
const chinaRegionOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(false)
const refreshTable = ref(true)
const needCreateParent = ref(false)
// 级联选择器配置
const cascaderProps = {
  value: 'code',
  label: 'name',
  children: 'children',
  emitPath: true,
  checkStrictly: false
}

const data = reactive({
  form: {
    isParentNode: false, // 新增字段
    regionPath: [] // 新增区域路径字段
  },
  queryParams: {
    name: null,
    regionStatus: null
  },
  rules: {
    name: [
      { required: true, message: "区域名称不能为空", trigger: "blur" }
    ],
    regionStatus: [
      { required: true, message: "区域状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 中国行政区划数据（完整版）
const initChinaRegionData = () => {
  chinaRegionOptions.value = chinaRegionData
}

/** 处理区域选择变化 */
const handleRegionChange = (value) => {
  if (!value || value.length === 0) {
    form.value.parentId = null
    needCreateParent.value = false
    return
  }
  
  // 检查是否需要创建父级区域
  checkNeedCreateParent(value)
}

/** 检查是否需要创建父级区域 */
const checkNeedCreateParent = async (regionPath) => {
  if (!regionPath || regionPath.length === 0) {
    needCreateParent.value = false
    return
  }
  
  // 检查每一级区域是否已存在
  let needCreate = false
  for (let i = 0; i < regionPath.length; i++) {
    const regionCode = regionPath[i]
    const exists = await checkRegionExists(regionCode)
    if (!exists) {
      needCreate = true
      break
    }
  }
  
  needCreateParent.value = needCreate
}

/** 检查区域是否存在 */
const checkRegionExists = async (regionCode, regionName) => {
  try {
    const response = await listRegion()
    const allRegions = response.data || []
    
    console.log('检查区域是否存在:', { regionCode, regionName, allRegions })
    
    // 在所有区域中查找是否存在相同的区域代码或名称
    const findRegion = (regions, code, name) => {
      for (let region of regions) {
        // 优先通过区域代码匹配，如果没有代码则通过名称匹配
        const matchByCode = region.regionCode && region.regionCode === code
        const matchByName = region.name && region.name === name
        
        if (matchByCode || matchByName) {
          console.log('找到匹配的区域:', region)
          return region
        }
        
        if (region.children && region.children.length > 0) {
          const found = findRegion(region.children, code, name)
          if (found) return found
        }
      }
      return null
    }
    
    const foundRegion = findRegion(allRegions, regionCode, regionName)
    return foundRegion ? foundRegion.id : null
  } catch (error) {
    console.error('检查区域存在性失败:', error)
    return null
  }
}

/** 获取区域路径文本 */
const getRegionPathText = () => {
  if (!form.value.regionPath || form.value.regionPath.length === 0) {
    return ''
  }
  
  const getRegionName = (code, options) => {
    for (let option of options) {
      if (option.code === code) {
        return option.name
      }
      if (option.children) {
        const childName = getRegionName(code, option.children)
        if (childName) return childName
      }
    }
    return ''
  }
  
  const names = form.value.regionPath.map(code => getRegionName(code, chinaRegionOptions.value))
  return names.join(' > ')
}

/** 自动创建父级区域 */
const handleCreateParentRegions = async () => {
  if (!form.value.regionPath || form.value.regionPath.length === 0) {
    return
  }
  
  console.log('开始创建父级区域，路径:', form.value.regionPath)
  
  // 获取最新的区域列表
  let currentRegions = null
  const refreshRegionList = async () => {
    try {
      const response = await listRegion()
      currentRegions = response.data || []
      console.log('刷新区域列表，当前区域数量:', currentRegions.length)
    } catch (error) {
      console.error('获取区域列表失败:', error)
      currentRegions = []
    }
  }
  
  // 在当前区域列表中查找区域
  const findRegionInList = (regions, code, name) => {
    for (let region of regions) {
      const matchByCode = region.regionCode && region.regionCode === code
      const matchByName = region.name && region.name === name
      
      if (matchByCode || matchByName) {
        console.log('在列表中找到匹配的区域:', region)
        return region
      }
      
      if (region.children && region.children.length > 0) {
        const found = findRegionInList(region.children, code, name)
        if (found) return found
      }
    }
    return null
  }
  
  // 初始获取区域列表
  await refreshRegionList()
  
  // 逐级创建区域
  let parentId = 0
  for (let i = 0; i < form.value.regionPath.length; i++) {
    const regionCode = form.value.regionPath[i]
    const regionName = getRegionNameByCode(regionCode)
    
    console.log(`处理第${i+1}级区域:`, { regionCode, regionName, currentParentId: parentId })
    
    // 在当前列表中检查区域是否已存在
    const existingRegion = findRegionInList(currentRegions, regionCode, regionName)
    if (existingRegion) {
      // 区域已存在，使用现有ID
      console.log(`区域"${regionName}"已存在，ID:`, existingRegion.id)
      parentId = existingRegion.id
    } else {
      // 创建新区域前先检查同级名称重复
      console.log(`创建新区域"${regionName}"前检查重复...`)
      
      // 在当前缓存中检查是否有同名区域
      const allRegionsFlat = []
      const flattenRegions = (regions) => {
        for (let region of regions) {
          allRegionsFlat.push(region)
          if (region.children && region.children.length > 0) {
            flattenRegions(region.children)
          }
        }
      }
      flattenRegions(currentRegions)
      
      const duplicateInCache = allRegionsFlat.filter(region => {
        const regionParentId = region.parentId === null || region.parentId === undefined ? 0 : region.parentId
        const currentParentId = parentId === null || parentId === undefined ? 0 : parentId
        return region.name === regionName && regionParentId === currentParentId
      })
      
      if (duplicateInCache.length > 0) {
        console.log(`区域"${regionName}"在父级${parentId}下已存在，跳过创建`)
        parentId = duplicateInCache[0].id
      } else {
        console.log(`创建新区域"${regionName}"`)
        const regionData = {
          name: regionName,
          parentId: parentId,
          regionStatus: 0, // 默认状态
          regionCode: regionCode,
          isAutoGenerated: 1, // 标记为自动生成的区域
          source: 'cascader' // 标记来源为级联选择器
        }
        
        try {
          const response = await addRegion(regionData)
          console.log(`区域"${regionName}"创建响应:`, response)
          
          // 确保响应数据结构正确
          let newRegionId = null
          if (response && response.data && response.data.id) {
            newRegionId = response.data.id
          } else if (response && response.id) {
            newRegionId = response.id
          } else if (response && response.msg && response.msg.includes('成功')) {
            // 如果只返回成功信息，需要重新查询获取ID
            await refreshRegionList()
            const newRegion = findRegionInList(currentRegions, regionCode, regionName)
            if (newRegion) {
              newRegionId = newRegion.id
            }
          }
          
          if (newRegionId) {
            parentId = newRegionId
            console.log(`区域"${regionName}"创建成功，ID:`, parentId)
            
            // 创建成功后立即刷新区域列表，确保后续检查基于最新数据
            await refreshRegionList()
          } else {
            console.error('创建区域响应格式异常:', response)
            throw new Error('无法获取创建区域的ID')
          }
        } catch (error) {
          console.error(`创建区域"${regionName}"失败:`, error)
          
          // 如果创建失败，可能是因为区域已经存在，尝试重新查询
          await refreshRegionList()
          const existingAfterError = findRegionInList(currentRegions, regionCode, regionName)
          if (existingAfterError) {
            console.log(`创建失败但区域已存在，使用现有ID:`, existingAfterError.id)
            parentId = existingAfterError.id
          } else {
            throw new Error(`创建区域"${regionName}"失败: ${error.message}`)
          }
        }
      }
    }
  }
  
  console.log('父级区域创建完成，最终父级ID:', parentId)
  
  // 设置最后一级为父级ID
  form.value.parentId = parentId
  needCreateParent.value = false
  
  return parentId
}

/** 根据区域代码获取区域名称 */
const getRegionNameByCode = (code) => {
  const getRegionName = (targetCode, options) => {
    for (let option of options) {
      if (option.code === targetCode) {
        return option.name
      }
      if (option.children) {
        const childName = getRegionName(targetCode, option.children)
        if (childName) return childName
      }
    }
    return ''
  }
  
  return getRegionName(code, chinaRegionOptions.value)
}

/** 根据区域代码获取区域ID */
const getRegionIdByCode = async (regionCode) => {
  // 复用checkRegionExists的逻辑
  const regionName = getRegionNameByCode(regionCode)
  return await checkRegionExists(regionCode, regionName)
}

/** 根据父级ID构建区域路径 */
const buildRegionPathByParentId = async (parentId) => {
  if (!parentId || parentId === 0) {
    return []
  }
  
  try {
    const response = await listRegion()
    const allRegions = response.data || []
    
    console.log('构建区域路径，父级ID:', parentId)
    
    // 查找父级区域
    const findRegionById = (regions, targetId) => {
      for (let region of regions) {
        if (region.id === targetId) {
          return region
        }
        if (region.children && region.children.length > 0) {
          const found = findRegionById(region.children, targetId)
          if (found) return found
        }
      }
      return null
    }
    
    // 从扁平数据中查找
    const findRegionByIdFlat = (regions, targetId) => {
      return regions.find(region => region.id === targetId)
    }
    
    const parentRegion = findRegionByIdFlat(allRegions, parentId)
    if (!parentRegion) {
      console.log('未找到父级区域:', parentId)
      return []
    }
    
    console.log('找到父级区域:', parentRegion)
    
    // 递归构建路径（从父级向上查找）
    const buildPath = (regions, targetRegion) => {
      const path = []
      let currentRegion = targetRegion
      
      while (currentRegion) {
        // 尝试在中国区域选项中查找匹配的区域代码
        const regionCode = findRegionCodeByName(currentRegion.name)
        if (regionCode) {
          path.unshift(regionCode)
        }
        
        // 查找父级区域
        if (currentRegion.parentId && currentRegion.parentId !== 0) {
          currentRegion = findRegionByIdFlat(regions, currentRegion.parentId)
        } else {
          currentRegion = null
        }
      }
      
      return path
    }
    
    const regionPath = buildPath(allRegions, parentRegion)
    console.log('构建的区域路径:', regionPath)
    
    return regionPath
  } catch (error) {
    console.error('构建区域路径失败:', error)
    return []
  }
}

/** 根据区域名称查找区域代码 */
const findRegionCodeByName = (regionName) => {
  const findCode = (options, name) => {
    for (let option of options) {
      if (option.name === name) {
        return option.code
      }
      if (option.children) {
        const found = findCode(option.children, name)
        if (found) return found
      }
    }
    return null
  }
  
  return findCode(chinaRegionOptions.value, regionName)
}

/** 检查同级区域名称是否重复 */
const checkSiblingRegionNameDuplicate = async (regionName, parentId, excludeId = null) => {
  try {
    const response = await listRegion()
    const allRegions = response.data || []
    
    console.log('检查同级区域名称重复:', { regionName, parentId, excludeId, allRegions })
    
    // 直接从扁平数据中查找同级区域
    const findSiblingRegions = (regions, targetParentId) => {
      // 标准化父级ID：null、undefined、0 都视为顶级
      const normalizeParentId = (pid) => {
        return pid === null || pid === undefined || pid === 0 ? 0 : pid
      }
      
      const normalizedTargetParentId = normalizeParentId(targetParentId)
      
      // 从扁平数据中筛选出同级区域
      const siblings = regions.filter(region => {
        const regionParentId = normalizeParentId(region.parentId)
        return regionParentId === normalizedTargetParentId
      })
      
      console.log(`查找父级ID ${normalizedTargetParentId} 下的同级区域:`, siblings)
      return siblings
    }
    
    const siblingRegions = findSiblingRegions(allRegions, parentId)
    console.log('找到同级区域:', siblingRegions)
    
    // 检查是否有同名的区域（排除当前编辑的区域）
    const duplicate = siblingRegions.find(region => {
      const isDuplicate = region.name === regionName && region.id !== excludeId
      if (isDuplicate) {
        console.log(`发现重复区域: ${region.name} (ID: ${region.id})`)
      }
      return isDuplicate
    })
    
    if (duplicate) {
      console.log('发现重复区域:', duplicate)
      return duplicate
    }
    
    console.log('未发现重复区域')
    return null
  } catch (error) {
    console.error('检查同级区域名称失败:', error)
    return null
  }
}

/** 查询区域信息管理列表 */
function getList() {
  loading.value = true
  listRegion(queryParams.value).then(response => {
    regionList.value = proxy.handleTree(response.data, "id", "parentId")
    loading.value = false
  })
}

/** 查询区域信息管理下拉树结构 */
function getTreeselect() {
  listRegion().then(response => {
    regionOptions.value = []
    const data = { id: 0, name: '无', children: [] }
    regionOptions.value=proxy.handleTree(response.data, "id", "parentId")
    regionOptions.value.push(data)
  })
}
	
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    parentId: null,
    regionStatus: 0,
    isParentNode: false, // 新增字段
    regionPath: [] // 重置区域路径
  }
  needCreateParent.value = false
  proxy.resetForm("regionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

// 状态处理方法 - 使用字典数据
function getStatusText(status) {
  const dict = region_status.value.find(item => item.value == status)
  return dict ? dict.label : '未知'
}

function getStatusClass(status) {
  // 根据字典中的状态值设置样式类
  const statusNum = parseInt(status)
  switch(statusNum) {
    case 0: return 'status-success'  // 正常
    case 1: return 'status-warning'  // 警告
    case 2: return 'status-danger'   // 危险
    default: return 'status-info'
  }
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 重置状态按钮操作 */
function handleResetStatus() {
  proxy.$modal.confirm('确定要将所有的状态信息设置为未检查吗？').then(function() {
    // 调用定时任务的执行一次功能，重置区域状态任务ID通常为4，任务组为DEFAULT
    return runJob(4, 'DEFAULT')
  }).then(() => {
    proxy.$modal.msgSuccess("状态重置成功")
    getList() // 重新加载列表
  }).catch(() => {})
}

/** 顶级新增按钮操作 */
function handleAddTopLevel() {
  reset()
  getTreeselect()
  form.value.parentId = 0
  open.value = true
  title.value = "添加区域信息管理"
}

/** 新增子区域按钮操作 */
function handleAdd(row) {
  // 检查是否可以新增子区域
  if (row && !canAddSubRegion(row)) {
    proxy.$modal.msgError('只有县级单位才能新增子区域')
    return
  }
  
  reset()
  getTreeselect()
  
  if (row != null && row.id) {
    form.value.parentId = row.id
    
    // 如果是县级单位，自动填充归属区域
    if (isCountyLevel(row)) {
      // 构建到该县级单位的完整路径
      buildRegionPathForCounty(row).then(regionPath => {
        if (regionPath && regionPath.length > 0) {
          form.value.regionPath = regionPath
          console.log('自动填充县级单位归属区域路径:', regionPath)
          // 触发区域变化处理
          handleRegionChange(regionPath)
        }
      })
    }
  } else {
    form.value.parentId = 0
  }
  
  open.value = true
  title.value = "添加区域信息管理"
}

/** 为县级单位构建区域路径 */
const buildRegionPathForCounty = async (countyRegion) => {
  try {
    const response = await listRegion()
    const allRegions = response.data || []
    
    console.log('为县级单位构建路径:', countyRegion.name)
    
    // 从扁平数据中查找
    const findRegionByIdFlat = (regions, targetId) => {
      return regions.find(region => region.id === targetId)
    }
    
    // 递归构建路径（从县级向上查找到省级）
    const buildPath = (regions, targetRegion) => {
      const path = []
      let currentRegion = targetRegion
      
      while (currentRegion) {
        // 尝试在中国区域选项中查找匹配的区域代码
        const regionCode = findRegionCodeByName(currentRegion.name)
        if (regionCode) {
          path.unshift(regionCode)
        }
        
        // 查找父级区域
        if (currentRegion.parentId && currentRegion.parentId !== 0) {
          currentRegion = findRegionByIdFlat(regions, currentRegion.parentId)
        } else {
          currentRegion = null
        }
      }
      
      return path
    }
    
    const regionPath = buildPath(allRegions, countyRegion)
    console.log('县级单位构建的区域路径:', regionPath)
    
    return regionPath
  } catch (error) {
    console.error('构建县级单位区域路径失败:', error)
    return []
  }
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 检查是否为系统保护的区域 */
const isProtectedRegion = (region) => {
  // 1. 检查是否标记为自动生成
  if (region.isAutoGenerated === 1 || region.isAutoGenerated === true) {
    return true
  }
  
  // 2. 检查是否有区域代码（来自级联选择器的标准区域）
  if (region.regionCode) {
    return true
  }
  
  // 3. 检查区域来源标记
  if (region.source === 'system' || region.source === 'cascader') {
    return true
  }
  
  // 4. 检查是否在中国区域选项中存在（临时兼容方案）
  // 这样可以保护现有的标准区域，即使它们没有上述标记
  if (region.name && isStandardRegionName(region.name)) {
    return true
  }
  
  return false
}

/** 检查是否为标准区域名称（在中国区域选项中存在） */
const isStandardRegionName = (regionName) => {
  // 递归搜索中国区域选项中是否存在该名称
  const searchInOptions = (options, name) => {
    for (let option of options) {
      if (option.name === name) {
        return true
      }
      if (option.children && option.children.length > 0) {
        if (searchInOptions(option.children, name)) {
          return true
        }
      }
    }
    return false
  }
  
  return searchInOptions(chinaRegionOptions.value, regionName)
}

/** 检查是否为县级单位 */
const isCountyLevel = (region) => {
  if (!region || !region.name) return false
  
  // 直接排除省级单位
  const provincePatterns = [
    /.*省$/, // 省
    /.*自治区$/, // 自治区
    /.*特别行政区$/, // 特别行政区
  ]
  
  // 排除直辖市（它们本身是省级）
  const municipalities = ['北京市', '上海市', '天津市', '重庆市']
  if (municipalities.includes(region.name)) {
    return false
  }
  
  // 排除省级单位
  if (provincePatterns.some(pattern => pattern.test(region.name))) {
    return false
  }
  
  // 排除地级市（通过检查是否在中国区域选项的第2层）
  const isPrefectureLevelCity = (options, name, level = 0) => {
    for (let option of options) {
      if (option.name === name && level === 1) {
        // 在第2层且以市结尾的是地级市
        return name.endsWith('市')
      }
      if (option.children && option.children.length > 0) {
        if (isPrefectureLevelCity(option.children, name, level + 1)) {
          return true
        }
      }
    }
    return false
  }
  
  // 如果是地级市，不是县级
  if (isPrefectureLevelCity(chinaRegionOptions.value, region.name)) {
    return false
  }
  
  // 检查是否在中国区域选项的县级层级（第3层或直辖市的第2层）
  const isCountyInOptions = (options, name, level = 0, parentName = '') => {
    for (let option of options) {
      if (option.name === name) {
        // 直辖市的区（第2层）或普通地级市的县区（第3层）
        if (level === 2 && municipalities.includes(parentName)) {
          return true // 直辖市的区
        }
        if (level === 2 && !municipalities.includes(parentName)) {
          return true // 地级市的县区
        }
        return false
      }
      if (option.children && option.children.length > 0) {
        if (isCountyInOptions(option.children, name, level + 1, option.name)) {
          return true
        }
      }
    }
    return false
  }
  
  // 检查县级命名模式（但不包括地级市）
  const countyPatterns = [
    /.*县$/, // 县
    /.*区$/, // 区（市辖区）
    /.*旗$/, // 旗
    /.*自治县$/, // 自治县
    /.*自治旗$/, // 自治旗
    /.*林区$/, // 林区
    /.*特区$/, // 特区
  ]
  
  // 只有在中国区域选项中且在县级层级的才是县级单位
  return isCountyInOptions(chinaRegionOptions.value, region.name)
}

/** 检查是否可以新增子区域 */
const canAddSubRegion = (region) => {
  // 如果不是被保护的区域（用户自己新增的区域），不允许新增子区域
  if (!isProtectedRegion(region)) {
    return false
  }
  
  // 如果是被保护的区域，只有县级单位才能新增子区域
  return isCountyLevel(region)
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  // 检查是否为系统保护的区域
  if (isProtectedRegion(row)) {
    proxy.$modal.msgError('系统保护的省份、城市信息不允许修改')
    return
  }
  
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentId = row.parentId
  }
  
  try {
    const response = await getRegion(row.id)
    const data = response.data
    form.value = response.data
    form.value.isParentNode = haveChildrenNode(regionList, form.value.id)
    
    // 根据父级ID构建区域路径
    if (form.value.parentId && form.value.parentId !== 0) {
      console.log('修改区域，构建区域路径，父级ID:', form.value.parentId)
      const regionPath = await buildRegionPathByParentId(form.value.parentId)
      form.value.regionPath = regionPath
      console.log('设置区域路径:', regionPath)
      
      // 检查是否需要创建父级区域
      handleRegionChange(regionPath)
    } else {
      form.value.regionPath = []
    }
    
    open.value = true
    title.value = "修改区域信息管理"
  } catch (error) {
    console.error('获取区域信息失败:', error)
    proxy.$modal.msgError('获取区域信息失败')
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["regionRef"].validate(async valid => {
    if (valid) {
      try {
        console.log('=== 开始提交表单验证 ===')
        console.log('表单数据:', form.value)
        
        // 检查同级区域名称是否重复
        console.log('开始检查同级区域名称重复...')
        const duplicateRegion = await checkSiblingRegionNameDuplicate(
          form.value.name, 
          form.value.parentId || 0, 
          form.value.id
        )
        
        if (duplicateRegion) {
          console.log('检测到重复区域，阻止提交:', duplicateRegion)
          proxy.$modal.msgError(`同一父级下已存在名为"${form.value.name}"的区域，请修改区域名称`)
          return
        }
        
        console.log('同级区域名称检查通过，继续提交...')
        
        // 如果选择了区域路径，先自动创建父级区域
        if (form.value.regionPath && form.value.regionPath.length > 0) {
          console.log('开始创建父级区域，路径:', form.value.regionPath)
          const parentId = await handleCreateParentRegions()
          console.log('父级区域创建完成，父级ID:', parentId)
          
          // 确保 parentId 被正确设置
          if (!form.value.parentId && parentId) {
            form.value.parentId = parentId
          }
          
          // 创建父级区域后再次检查同级名称重复
          const duplicateAfterParentCreation = await checkSiblingRegionNameDuplicate(
            form.value.name, 
            form.value.parentId || 0, 
            form.value.id
          )
          
          if (duplicateAfterParentCreation) {
            proxy.$modal.msgError(`同一父级下已存在名为"${form.value.name}"的区域，请修改区域名称`)
            return
          }
        }
        
        console.log('准备提交表单，数据:', form.value)
        
        if (form.value.id != null) {
          await updateRegion(form.value)
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          const response = await listRegion()
          regionList.value = proxy.handleTree(response.data, "id", "parentId")
          loading.value = false
          handleUpdateParentNodeStatus(form.value)
        } else {
          const response = await addRegion(form.value)
          console.log('区域创建响应:', response)
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
          const listResponse = await listRegion()
          regionList.value = proxy.handleTree(listResponse.data, "id", "parentId")
          loading.value = false
          if (response && (response.data || response.id)) {
            handleUpdateParentNodeStatus(form.value)
          }
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        proxy.$modal.msgError('操作失败：' + (error.msg || error.message || error))
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 检查是否为系统保护的区域
  if (isProtectedRegion(row)) {
    proxy.$modal.msgError('系统保护的省份、城市信息不允许删除')
    return
  }
  
  proxy.$modal.confirm('是否确认删除区域信息管理编号为"' + row.id + '"的数据项？').then(function() {
    return delRegion(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

//获取节点路径上的所有祖先
function getAncestors(regionList, nodeId) {
  const path = []

  function findNode(nodes, targetId, currentPath = []) {
    for (let node of nodes) {
      if (node.id === targetId) {
        return [...currentPath]
      }
      const newPath = [...currentPath, node]
      if (node.children) {
        const result = findNode(node.children, targetId, newPath)
        if (result) return result
      }
    }
    return null
  }

  return findNode(regionList.value, nodeId) || []
}

//根据子节点集合获取最优状态
function getBestStatus(children) {
  let highregion=ref(0)

  for (let child of children) {
    if (child.regionStatus === 2) {
      highregion.value = 2
      break
    } else if (child.regionStatus === 1) {
      highregion.value =1
    }
  }
  return highregion.value
}

/** 更新父节点状态 */
async function handleUpdateParentNodeStatus(updatedNode) {
  let form_dad =reactive({
    id:null,
    regionStatus:null,
    name:null,
    parentId:null
  })
  let updateNode_full=reactive()
  updateNode_full=updatedNode
  let ancestors_length=getAncestors(regionList, updatedNode.id).length
  for (let i = ancestors_length - 1; i >= 0; i--) {
    
    let ancestors = getAncestors(regionList, updateNode_full.id)
    const parent = ancestors[i]
    const siblings = parent.children || []
     // 获取当前子节点状态中的最优状态
     const bestStatus = getBestStatus(siblings)
    form_dad.id = parent.id
    form_dad.regionStatus= bestStatus
    try {
      await updateRegion(form_dad)
      let response=await listRegion()
      regionList.value=proxy.handleTree(response.data, "id", "parentId")
        // 如果需要每次更新后刷新列表，也可以保留
      updateNode_full=form_dad
    } catch (error) {
      proxy.$modal.msgError(`更新失败: ${parent.id}`)
      console.error(error)
    }
    
  }
}
function haveChildrenNode(tree, nodeId) {
  const descendants = getDescendants(tree, nodeId)
  return descendants.length > 0
}

//获取某节点的所有子节点
function getDescendants(tree, nodeId) {
  let descendants = []

  function traverse(nodes, targetId) {
    for (let node of nodes) {
      if (node.id === targetId && node.children) {
        // 找到目标节点，收集其所有子节点（扁平化）
        collectChildren(node.children)
      } else if (node.children) {
        traverse(node.children, targetId)
      }
    }
  }

  function collectChildren(children) {
    for (let child of children) {
      descendants.push(child)
      if (child.children) {
        collectChildren(child.children)
      }
    }
  }

  traverse(tree.value, nodeId)
  return descendants
}

// 初始化数据
initChinaRegionData()
getList()
</script>

<style scoped lang="scss">
@import '@/assets/styles/system-pages.scss';

// Region specific styles
.region-name {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .region-icon {
    font-size: 16px;
    color: var(--accent-blue);
  }
  
  span {
    font-weight: 500;
    color: var(--text-primary);
  }
}

// Tree table specific styles
:deep(.el-table) {
  .el-table__expand-icon {
    color: var(--accent-blue);
    
    &.el-table__expand-icon--expanded {
      transform: rotate(90deg);
    }
  }
  
  .el-table__indent {
    border-left: 1px dashed rgba(122, 156, 198, 0.3);
  }
  
  .el-table__placeholder {
    display: none;
  }
}

// Action button enhancements
.table-actions {
  .action-btn {
    &:not(.action-btn--primary):not(.action-btn--danger) {
      background: linear-gradient(135deg, var(--accent-success), #8fbc8f);
      
      &:hover {
        background: linear-gradient(135deg, #8fbc8f, var(--accent-success));
        transform: translateY(-1px);
      }
    }
  }
}

// Region status enhancements
.glass-status-tag {
  &.status-success {
    background: rgba(143, 188, 143, 0.1);
    color: var(--accent-success);
    border: 1px solid rgba(143, 188, 143, 0.3);
  }
  
  &.status-warning {
    background: rgba(255, 193, 7, 0.1);
    color: #ffc107;
    border: 1px solid rgba(255, 193, 7, 0.3);
  }
  
  &.status-danger {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
    border: 1px solid rgba(220, 53, 69, 0.3);
  }
  
  &.status-info {
    background: rgba(13, 202, 240, 0.1);
    color: #0dcaf0;
    border: 1px solid rgba(13, 202, 240, 0.3);
  }
}

// Time display enhancement
.el-table-column {
  .time-info {
    display: flex;
    align-items: center;
    gap: 6px;
    
    .time-icon {
      font-size: 14px;
      color: var(--text-secondary);
    }
  }
}

// 区域管理专用的玻璃拟态按钮样式
.table-actions {
  .action-btn--region-glass {
    background: rgba(255, 255, 255, 0.1);
    color: #a5d6a7;
    border-color: rgba(76, 175, 80, 0.05);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    
    &:hover {
      background: rgba(255, 255, 255, 0.15);
      color: #81c784;
      border-color: rgba(76, 175, 80, 0.1);
    }
  }
  
  // 禁用按钮样式
  .action-btn--disabled {
    opacity: 0.6;
    cursor: not-allowed;
    background: rgba(255, 255, 255, 0.08) !important;
    color: rgba(255, 255, 255, 0.5) !important;
    border-color: rgba(255, 255, 255, 0.2) !important;
    
    &:hover {
      background: rgba(255, 255, 255, 0.08) !important;
      color: rgba(255, 255, 255, 0.5) !important;
      border-color: rgba(255, 255, 255, 0.2) !important;
      transform: none !important;
      box-shadow: none !important;
    }
    
    // 确保图标也是可见的
    .svg-icon {
      opacity: 1;
    }
  }
}

// 自动生成标签样式
.auto-generated-tag {
  margin-left: 8px;
  background: rgba(144, 202, 249, 0.2) !important;
  color: #90caf9 !important;
  border: 1px solid rgba(144, 202, 249, 0.3) !important;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
}

// 区域名称样式增强
.region-name {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .auto-generated-tag {
    flex-shrink: 0;
  }
}

// 区域选择器样式
.region-selector {
  .region-info {
    margin-top: 12px;
    padding: 12px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    
    .region-path {
      display: block;
      color: var(--text-secondary);
      font-size: 13px;
      line-height: 1.4;
    }
  }
}

// 级联选择器样式优化
:deep(.el-cascader) {
  .el-cascader__tags {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 6px;
  }
  
  .el-tag {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: var(--text-primary);
    
    .el-tag__close {
      color: var(--text-secondary);
      
      &:hover {
        color: var(--accent-blue);
      }
    }
  }
}

@media (max-width: 768px) {
  .region-name {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .region-selector {
    .region-info {
      padding: 8px;
      
      .region-path {
        font-size: 12px;
      }
    }
  }
}
</style>
